/**
 * Socket.io事件类型定义
 * 提供类型安全的Socket.io事件处理
 */

import { Socket as ClientSocket } from 'socket.io-client';
import { Socket as ServerSocket } from 'socket.io';
import { Editor } from '@tiptap/react';
import { DocumentConflict } from './document';

// Socket事件类型
export type SocketEvent = 
  | 'connect'
  | 'disconnect'
  | 'reconnect'
  | 'error'
  | 'notification'
  | 'project:join'
  | 'project:leave'
  | 'project:member:joined'
  | 'project:member:left'
  | 'document:update'
  | 'document:cursor'
  | 'document:comment'
  | 'document:suggestion'
  | 'document:lock'
  | 'document:unlock'
  | 'user:status'
  | 'user:activity'
  | 'permission:change'
  | 'block:edit'
  | 'document:revision'
  | 'document:conflict';

// 权限级别
export type PermissionLevel = 
  | 'owner'     // 所有权限，包括删除项目
  | 'admin'     // 管理权限，包括邀请成员、管理权限
  | 'editor'    // 编辑权限，可以编辑文档
  | 'commenter' // 评论权限，只能添加评论和建议
  | 'viewer';   // 只读权限，只能查看文档

// 用户状态类型
export type UserStatus = 'online' | 'away' | 'busy' | 'offline';

// 用户活动类型
export type UserActivity = 'editing' | 'viewing' | 'commenting' | 'suggesting' | 'idle';

// 基础数据结构
interface BaseEventData {
  timestamp: number;
}

// 用户简要信息
export interface UserInfo {
  id: string;
  name: string;
  image?: string;
}

// 范围选择数据
export interface RangeData {
  from: number;
  to: number;
}

// 项目更新数据
export interface ProjectUpdateData extends BaseEventData {
  projectId: string;
  updatedBy: UserInfo;
  update: any;
}

// 文档锁定数据
export interface DocumentLockData extends BaseEventData {
  projectId: string;
  docId: string;
  userId: string;
  userName: string;
}

// 文档更新数据
export interface DocumentUpdateData extends BaseEventData {
  projectId: string;
  docId: string;
  update: {
    content: any;
    version: number;
  };
  updatedBy: UserInfo;
}

// 光标位置数据
export interface CursorPositionData extends BaseEventData {
  projectId: string;
  docId: string;
  userId: string;
  userName: string;
  userColor?: string;
  position: {
    index?: number;
    from?: number;
    to?: number;
  };
}

// 块编辑数据
export interface BlockEditData extends BaseEventData {
  projectId: string;
  docId: string;
  userId: string;
  userName: string;
  userColor?: string;
  blockId: string;
  isEditing: boolean;
}

// 评论数据
export interface CommentData extends BaseEventData {
  id: string;
  projectId: string;
  docId: string;
  content: string;
  author: UserInfo;
  replyTo?: string;
  range?: RangeData;
  status: 'active' | 'resolved' | 'deleted';
  replies?: CommentReply[];
}

export interface CommentReply {
  id: string;
  content: string;
  author: UserInfo;
  createdAt: string;
}

// 建议数据
export interface SuggestionData extends BaseEventData {
  id: string;
  projectId: string;
  docId: string;
  content: string;
  note: string;
  author: UserInfo;
  suggestedContent: any;
  originalContent: any;
  range?: RangeData;
  status: 'pending' | 'accepted' | 'rejected';
}

// 通知数据
export interface NotificationData extends BaseEventData {
  id: string;
  userId: string;
  title: string;
  message: string;
  type: 'info' | 'success' | 'warning' | 'error';
  link?: string;
  read: boolean;
}

// 成员数据
export interface MemberData extends BaseEventData {
  projectId: string;
  user: UserInfo;
  role: PermissionLevel;
}

// 用户状态数据
export interface UserStatusData extends BaseEventData {
  userId: string;
  userName: string;
  userImage?: string;
  status: UserStatus;
}

// 用户活动数据
export interface UserActivityData extends BaseEventData {
  projectId: string;
  userId: string;
  userName: string;
  activity: UserActivity;
  resourceId?: string;  // 文档ID或其他资源ID
  resourceType?: string; // 'document', 'task', 等
}

// 打字状态数据
export interface TypingData extends BaseEventData {
  projectId: string;
  docId?: string;
  taskId?: string;
  userId: string;
  userName: string;
}

// 权限变更数据
export interface PermissionChangeData extends BaseEventData {
  projectId: string;
  userId: string;
  changedBy: UserInfo;
  oldPermission: PermissionLevel;
  newPermission: PermissionLevel;
}

// 冲突数据
export interface ConflictData extends BaseEventData {
  projectId: string;
  docId: string;
  localContent: any;
  remoteContent: any;
  remoteUser: UserInfo;
}

// 文档修订版本数据
export interface DocumentRevisionData extends BaseEventData {
  projectId: string;
  docId: string;
  revision: {
    id: string;
    content: any;
    version: number;
    createdBy: UserInfo;
    message?: string;
  };
}

// 文档节点数据
export interface DocumentNodeData {
  id: string; // 节点唯一ID
  type: string; // 节点类型 (paragraph, heading, etc.)
  content?: any; // 节点内容
}

// 文档节点锁定数据
export interface NodeLockData extends BaseEventData {
  projectId: string;
  docId: string;
  nodeId: string;
  userId: string;
  userName: string;
  userColor?: string;
  locked: boolean;
}

// 文档建议数据 (扩展现有SuggestionData)
export interface DocumentSuggestionData extends SuggestionData {
  nodeId: string; // 建议所针对的节点ID
  suggestedOperation: 'replace' | 'insert' | 'delete';
}

// 连接状态
export interface ConnectionState {
  status: 'connected' | 'disconnected' | 'connecting' | 'reconnecting';
  lastConnected?: number;
  reconnectAttempt?: number;
  error?: string;
}

// 客户端发送到服务器的事件
export interface ClientToServerEvents {
  'ping': (callback: (serverTime: number) => void) => void;
  'join-project': (projectId: string) => void;
  'leave-project': (projectId: string) => void;
  'join-task': (taskId: string) => void;
  'leave-task': (taskId: string) => void;
  'task-update': (data: any) => void;
  'new-comment': (data: CommentData) => void;
  'doc-update': (data: DocumentUpdateData) => void;
  'cursor-move': (data: CursorPositionData) => void;
  'block-edit': (data: BlockEditData) => void;
  'new-suggestion': (data: SuggestionData) => void;
  'doc-lock': (data: DocumentLockData) => void;
  'doc-unlock': (data: DocumentLockData) => void;
  'user-status': (status: UserStatus) => void;
  'user-activity': (data: UserActivityData) => void;
  'typing-start': (data: TypingData) => void;
  'typing-end': (data: TypingData) => void;
  'permission-change': (data: PermissionChangeData) => void;
  'doc-revision': (data: DocumentRevisionData, callback?: (success: boolean) => void) => void;
  'node-lock': (data: NodeLockData, callback?: (success: boolean) => void) => void;
  'node-unlock': (data: NodeLockData) => void;
  'resolve-suggestion': (data: {suggestionId: string, accepted: boolean, resolvedBy: UserInfo, timestamp: number}, callback?: (success: boolean) => void) => void;
  'resolve-conflict': (data: {conflictId: string, resolution: any, resolvedBy: UserInfo, timestamp: number}, callback?: (success: boolean) => void) => void;
}

// 服务器发送到客户端的事件
export interface ServerToClientEvents {
  'pong': (serverTime: number, latency: number) => void;
  'task-updated': (data: any) => void;
  'new-comment-added': (data: CommentData) => void;
  'doc-updated': (data: DocumentUpdateData) => void;
  'cursor-moved': (data: CursorPositionData) => void;
  'block-editing': (data: BlockEditData) => void;
  'new-suggestion-added': (data: SuggestionData) => void;
  'user-status-changed': (data: UserStatusData) => void;
  'user-activity-update': (data: UserActivityData) => void;
  'user-typing': (data: TypingData) => void;
  'user-stopped-typing': (data: TypingData) => void;
  'notification': (data: NotificationData) => void;
  'project-updated': (data: ProjectUpdateData) => void;
  'member-joined': (data: MemberData) => void;
  'member-left': (data: MemberData) => void;
  'user-joined': (data: any) => void; // 添加用户加入事件
  'user-left': (data: any) => void; // 添加用户离开事件
  'doc-locked': (data: DocumentLockData) => void;
  'doc-unlocked': (data: DocumentLockData) => void;
  'permission-changed': (data: PermissionChangeData) => void;
  'doc-revision-added': (data: DocumentRevisionData) => void;
  'node-locked': (data: NodeLockData) => void;
  'node-unlocked': (data: NodeLockData) => void;
  'conflict-detected': (data: ConflictData) => void;
}

// 定义类型化的Socket
export type TypedClientSocket = ClientSocket<ServerToClientEvents, ClientToServerEvents>;
export type TypedServerSocket = ServerSocket<ClientToServerEvents, ServerToClientEvents>;

// Socket上下文类型
export interface SocketContextType {
  socket: TypedClientSocket | null;
  isConnected: boolean;
  connectionState: ConnectionState;
  error: string | null;
  latency: number;
  offlineMode: boolean; // 是否处于离线模式
  
  // 房间管理
  joinProject: (projectId: string) => void;
  leaveProject: (projectId: string) => void;
  joinTask: (taskId: string) => void;
  leaveTask: (taskId: string) => void;
  
  // 任务相关
  sendTaskUpdate: (data: any) => void;
  sendComment: (data: CommentData) => void;
  
  // 文档相关
  sendDocUpdate: (data: DocumentUpdateData) => void;
  sendCursorPosition: (data: CursorPositionData) => void;
  sendBlockEdit: (data: BlockEditData) => void;
  sendSuggestion: (data: SuggestionData) => void;
  lockDocument: (data: DocumentLockData) => void;
  unlockDocument: (data: DocumentLockData) => void;
  
  // 用户状态
  setUserStatus: (status: UserStatus) => void;
  setUserActivity: (data: UserActivityData) => void;
  startTyping: (data: TypingData) => void;
  stopTyping: (data: TypingData) => void;
  
  // 权限相关
  changePermission: (data: PermissionChangeData) => void;
  
  // 事件监听
  onTaskUpdated: (handler: (data: any) => void) => () => void;
  onCommentAdded: (handler: (data: CommentData) => void) => () => void;
  onDocUpdated: (handler: (data: DocumentUpdateData) => void) => () => void;
  onCursorMoved: (handler: (data: CursorPositionData) => void) => () => void;
  onBlockEditing: (handler: (data: BlockEditData) => void) => () => void;
  onSuggestionAdded: (handler: (data: SuggestionData) => void) => () => void;
  onUserStatusChanged: (handler: (data: UserStatusData) => void) => () => void;
  onUserActivity: (handler: (data: UserActivityData) => void) => () => void;
  onUserTyping: (handler: (data: TypingData) => void) => () => void;
  onUserStoppedTyping: (handler: (data: TypingData) => void) => () => void;
  onNotification: (handler: (data: NotificationData) => void) => () => void;
  onProjectUpdated: (handler: (data: ProjectUpdateData) => void) => () => void;
  onMemberJoined: (handler: (data: MemberData) => void) => () => void;
  onMemberLeft: (handler: (data: MemberData) => void) => () => void;
  onDocumentLocked: (handler: (data: DocumentLockData) => void) => () => void;
  onDocumentUnlocked: (handler: (data: DocumentLockData) => void) => () => void;
  onPermissionChanged: (handler: (data: PermissionChangeData) => void) => () => void;
  
  // 连接管理
  reconnect: () => void;
  disconnect: () => void;
} 

// 协作上下文类型
export interface CollaborationContextType {
  // 状态
  activeUsers: UserInfo[];
  documentVersion: number;
  lockedNodes: Record<string, UserInfo>;
  userColors: Record<string, string>;
  revisions: DocumentRevisionData[];
  suggestions: DocumentSuggestionData[];
  conflicts: DocumentConflict[];
  editor: Editor | null;
  
  // 操作
  lockNode: (nodeId: string) => Promise<boolean>;
  unlockNode: (nodeId: string) => void;
  saveRevision: (content: any, message?: string) => Promise<void>;
  addSuggestion: (suggestion: Omit<DocumentSuggestionData, 'id' | 'timestamp'>) => Promise<void>;
  resolveSuggestion: (suggestionId: string, accepted: boolean) => Promise<void>;
  resolveConflict: (conflictId: string, resolution: any) => Promise<void>;
  registerEditor?: (editor: Editor) => void;
  compareRevisions?: (revisionA: DocumentRevisionData, revisionB: DocumentRevisionData) => { isDifferent: boolean; differences: string[] };
  mergeRevisions?: (baseRevision: DocumentRevisionData, incomingRevision: DocumentRevisionData) => any;
  
  // 状态
  isEditingAllowed: boolean;
  isCommentingAllowed: boolean;
  isSuggestingAllowed: boolean;
  hasConflicts: boolean;
  hasPendingSuggestions: boolean;
} 